package com.gt.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.gt.constant.MessageConstant;
import com.gt.context.BaseContext;
import com.gt.exception.BaseException;
import com.gt.exception.DeletionNotAllowedException;
import com.gt.mapper.BookMapper;
import com.gt.mapper.CategoryMapper;
import com.gt.pojo.PageResult;
import com.gt.pojo.dto.CategoryDTO;
import com.gt.pojo.dto.CategoryPageQueryDTO;
import com.gt.pojo.entity.Category;
import com.gt.pojo.vo.CategoryVO;
import com.gt.service.BookService;
import com.gt.service.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private BookMapper bookMapper;
    @Override
    public void save(CategoryDTO categoryDTO) {

        if (categoryDTO.getName().isEmpty()){
            throw new BaseException("分类不能为空");
        }
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO,category);
        //设置创建时间、修改时间、创建人、修改人
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        category.setCreateUser(BaseContext.getCurrentId());
        category.setUpdateUser(BaseContext.getCurrentId());
        categoryMapper.insert(category);
    }

    @Override
    public PageResult pageQuery(CategoryPageQueryDTO categoryPageQueryDTO) {
        PageHelper.startPage(categoryPageQueryDTO.getPage(),categoryPageQueryDTO.getPageSize());
        Page<CategoryVO> page = categoryMapper.pageQuery(categoryPageQueryDTO);
        PageResult pageResult = new PageResult(page.getTotal(),page.getResult());
        return pageResult;
    }

    @Override
    public void deleteById(Long id) {
        Integer count = bookMapper.getByCategoryId(id);
        if(count >0){
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
        }
        categoryMapper.deleteById(id);
    }

    @Override
    public void update(CategoryDTO categoryDTO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO,category);


        category.setUpdateTime(LocalDateTime.now());
        category.setUpdateUser(BaseContext.getCurrentId());

        categoryMapper.update(category);
    }
}
